package testJdk.io.testClone;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

import java.io.*;
import java.util.Date;

/**
 * @Description : 通过序列化机制深克隆对象
 * Created by cyd on 2021-04-27 22:43:14
 */
public class TestDeepClone {
    public static void main(String[] args) {
        Employee02 jack = new Employee02("jack", 20d, new Date());
        Employee02 jack02 = (Employee02)jack.clone();
        System.out.println(jack02==jack);
    }
}

class SerialCloneable implements Cloneable, Serializable {

    @SneakyThrows
    @Override
    public Object clone(){
        // 缓存对象
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bout);
        out.writeObject(this);
        out.close();

        // 回读对象
        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
        ObjectInputStream in = new ObjectInputStream(bin);
        Object o = in.readObject();
        in.close();

        return o;
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class Employee02 extends SerialCloneable{
    private String name;
    private Double salary;
    private Date birthday;
}
